package com.anntly.strategy.impl;

import com.anntly.config.DBRouterConfigProperties;
import com.anntly.context.DbContextHolder;
import com.anntly.strategy.IDbRoute;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author：Anntly
 * @Package：com.anntly.strategy.impl
 * @Project：dbRouter
 * @name：DbRouteHashPolicy
 * @Date：2024/7/7 16:04
 * @Filename：DbRouteHashPolicy
 */
public class DbRouteHashPolicy implements IDbRoute {

    @Resource
    private DBRouterConfigProperties dbRouterConfigProperties;

    @Override
    public void route(String routeValue) {
        Integer dbCount = dbRouterConfigProperties.getDbCount();
        Integer tableCount = dbRouterConfigProperties.getTableCount();
        int size = dbCount * tableCount;
        int index = (routeValue.hashCode()) ^ (routeValue.hashCode() >>> 16) & (size - 1);
        int dbIndex = index / tableCount + 1;
        int tbIndex = index - (dbIndex - 1) * tableCount;
        DbContextHolder.setDbRouteKey(String.format("%2d", dbIndex));
        DbContextHolder.setTbRouteKey(String.format("%3d", tbIndex));
    }

    @Override
    public void clear() {
        DbContextHolder.clear();
    }
}
